package swing;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Computer extends JFrame implements ActionListener {//监听接口
	private static final long serialVersionUID=1L;
	private JTextField tf;
	private JButton clear;
	public Computer(){
		setTitle("简易计算机");//窗口名
		setSize(220, 220);//长宽大小
		setVisible(true);//可视化窗口
		setLocation(100,80);//布局
		setDefaultCloseOperation(EXIT_ON_CLOSE);//关闭窗口
		JPanel top=new JPanel();//创建top面板
		top.setLayout(new BorderLayout());//设置top顶部面板布局
		JPanel center=new JPanel();//创建center中心面板
		add(top,BorderLayout.NORTH);//在top面板北边添加边界布局
		add(center);//添加中心面板
		tf=new JTextField();//创建文本框tf
		clear=new JButton("清除");//创建清除按钮
		clear.addActionListener(this);
		top.add(tf);top.add(clear,BorderLayout.EAST);//在顶部面板添加文本框tf
		String[] str={"7","8","9","+","4","5","6","-","1","2","3","*","0",".","/","="};
		center.setLayout(new GridLayout(4, 4));//在中心面板创建四行四列的表格
		for(int i=0;i<str.length;i++){
		JButton bt=new JButton(str[i]);
		bt.addActionListener(this);//添加tf按钮监听接口
		center.add(bt);
		}
	}
    public static void main(String[] args) {//main方法
		SwingUtilities.invokeLater( new Runnable() {
			public void run() {
				new Computer();
			}
		});
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd=e.getActionCommand();
		if(cmd.equals("清除")){
			tf.setText("");
		}
		else if(".0123456789".indexOf(cmd)>=0){
			String text=tf.getText();
			tf.setText(text+cmd);
		}
		else{
			
		}
	}
}
